#include<iostream>
using namespace std;

struct ListNode {
    int val;
    ListNode* next;
    ListNode(int x) : val(x), next(NULL) {}
};

class Solution {
public:
    ListNode* reverseKGroup(ListNode* head, int k) {
        if (head == NULL || k < 2) return head;
        int count = 0;
        ListNode* cur = head;
        while (cur) {
            cur = cur->next;
            ++count;
        }
        if (count < k) return head;
        ListNode* res = head;
        ListNode* last = NULL;
        while (head&& count/ k >0) {
            ListNode* prev = NULL;
            ListNode* cur = head;
            int cnt = 0;
            while (cnt < k) {
                ++cnt;
                ListNode* tmp = cur->next;
                cur->next = prev;
                prev = cur;
                cur = tmp;
            }
            if (last != NULL)
                last->next = prev;
            else
                res = prev;
            last = head;
            head = cur;
            count -= k;
        }
        if(last!=NULL)
            last->next = head;
        return res;
    }
};

//class Solution {
//public:
//    ListNode* reverseKGroup(ListNode* head, int k) {
//        if (head == NULL || k < 2) return head;
//        int count = 0;
//        ListNode* cur = head;
//        while (cur != NULL && ++count < k)
//            cur = cur->next;
//        ListNode* prev = head;
//        cur = head;
//        if (count == k) {
//            prev = NULL;
//            count = 0;
//            while (cur != NULL && count < k) {
//                ListNode* tmp = cur->next;
//                cur->next = prev;
//                prev = cur;
//                cur = tmp;
//                ++count;
//            }
//            head->next = reverseKGroup(cur, k);
//        }
//        return prev;
//    }
//};